<template>
  <div  >
    <el-card
      shadow="never"
      style="margin: 15px 0px"
       
      :body-style="{ padding: '0px' }"
      :page-size="pageSize"
      :total="total"
      :current-page="page"
      @current-change="currentChangeHandle"
    >
      <div class="search-box">
        <el-form ref="form" inline :model="form" @submit.native.prevent>
          <el-form-item prop="rowUniqueKeyLike">
            <el-input
              v-model="form.rowUniqueKeyLike"
              size="small"
              :placeholder="$t('common.device_sn')"
              @blur="
                () => (form.rowUniqueKeyLike = form.rowUniqueKeyLike.trim())
              "
              @keyup.enter.native="fetchData"
            />
          </el-form-item>
          <el-form-item v-show="showFormItem('STATUS')">
            <el-select
              v-model="status"
              size="small"
              :placeholder="$t('flyparam.param_file_status')"
              clearable
            >
              <el-option :label="$t('flyparam.file_status_1')" :value="-1" />
              <el-option :label="$t('flyparam.file_status_2')" :value="2" />
              <el-option :label="$t('flyparam.file_status_3')" :value="3" />
              <el-option :label="$t('flyparam.file_status_4')" :value="4" />
              <el-option :label="$t('flyparam.file_status_5')" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item v-show="showFormItem('ORGANIZATION')">
            <!--<el-select size="small" placeholder="Org" v-model="org">
          <el-option v-for="org in orgs" :key="org.orgId" :label="org.orgName" :value="org.orgId" />
            </el-select>-->
            <organization-select
              ref="organizationTree"
              size="small"
              :parent-org-id="orgId"
              :default-org-id="orgId"
              :auto-init="false"
              :list-data="orgs"
              :selected-org.sync="queryOrg"
            />
          </el-form-item>
          <el-form-item v-if="showFormItem('ORGANIZATION')">
            <el-checkbox
              v-model="subOrgFlag"
              :true-label="1"
              :false-label="0"
              border
              size="small"
              >{{ $t('modules.tms.merchant.sub_organization') }}</el-checkbox
            >
          </el-form-item>
          <el-form-item v-if="showFormItem('UPDATE_SCHEDULE')">
            <!--<el-checkbox
              v-model="isInUpdateSchedule"
              :true-label="1"
              :false-label="0"
              border
              size="small"
            >{{ $t('menu.M_12401006') }}</el-checkbox>-->
            <el-select
              v-model="isInUpdateSchedule"
              size="small"
              :placeholder="$t('flyparam.in_update_schedule')"
              clearable
              style="margin-right: 0px"
              @change="bindUpdateScheduleStateChange"
            >
              <el-option
                v-for="item in bindUpdateScheduleStates"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="showFormItem('FILE_PUBLISH_PROGRESS')">
            <!--<el-checkbox
              v-model="isFilePublishing"
              :true-label="1"
              :false-label="0"
              border
              size="small"
            >{{ $t('flyparam.terminal_file_generate_queue') }}</el-checkbox>-->
            <el-select
              v-model="isFilePublishing"
              size="small"
              :placeholder="$t('flyparam.terminal_param_file_publishing')"
              clearable
              style="margin-right: 0px; width: 250px"
              @change="filePublishStateChange"
            >
              <el-option
                v-for="item in filePublishStates"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-tooltip :content="$t('common.search')" placement="top">
              <el-button
                type="primary"
                class="align-middle p-1.5"
                size="medium"
                @click="
                  () => {
                    page = 1
                    fetchData()
                  }
                "
              >
                <svg-icon icon-class="search" class-name="text-lg" />
              </el-button>
            </el-tooltip>
          </el-form-item>
          <el-form-item
            v-permission="{ permission: PERMISSIONS.CONFIGURATION }"
          >
            <el-tooltip :content="$t('flyparam.new_terminal')" placement="top">
              <el-button
                size="medium"
                class="align-middle p-1.5"
                type="primary"
                @click="handleAddTerminal"
              >
                <svg-icon icon-class="plus" class-name="text-lg" />
              </el-button>
            </el-tooltip>
          </el-form-item>
          <el-form-item>
            <el-tooltip
              :content="$t('common.import') + ' / ' + $t('common.export')"
              placement="top"
            >
              <el-button
                size="medium"
                class="p-1.5 align-middle inline-block"
                type="primary"
                @click="importExportVisible = true"
              >
                <svg-icon icon-class="import-export" class-name="form-icon" />
              </el-button>
            </el-tooltip>
          </el-form-item>

          <el-form-item
            v-permission="{ permission: PERMISSIONS.CONFIGURATION }"
          >
            <el-tooltip
              :content="$t('flyparam.batch_operation')"
              placement="top"
            >
              <el-button
                size="medium"
                class="align-middle p-1.5"
                type="primary"
                @click="() => (dryrunVisible = true)"
              >
                <svg-icon icon-class="dryrun" class-name="text-lg" />
              </el-button>
            </el-tooltip>
          </el-form-item>

          <el-form-item style="float: right">
            <el-button size="medium" class="p-2" type="primary">
              <table-column-filter
                :list="settingList"
                :default-setting="defaultSettings"
                v-model:settings="settings"
                domain="tms.flyparam.list"
              />
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="tableLoading" :data="tableData">
        <el-table-column :label="$t('common.device_sn')" prop="name" />
        <el-table-column
          :label="$t('common.organization')"
          prop="orgName"
          width="170px"
        />
        <!--<el-table-column :label="$t('common.update_time')" prop="updTime" />-->
        <el-table-column
          :label="$t('flyparam.param_file_version')"
          prop="version"
          align="center"
        >
          <template v-slot="scope">
            <el-tag v-show="scope.row.version" size="small">{{
              scope.row.version
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('flyparam.param_file_status')"
          prop="status"
          align="center"
          width="170px"
        >
          <template v-slot="scope">
            <el-tooltip
              v-if="[3, 4, 5].includes(scope.row.status)"
              class="item"
              effect="dark"
              :content="contentFilter(scope.row)"
              placement="top-start"
            >
              <el-tag
                size="small"
                :type="tagFilter(scope.row.status) "
                disable-transitions
                >{{ statusFilter(scope.row.status)  }}</el-tag
              >
            </el-tooltip>
            <el-tag
              v-else
              size="small"
              :type="tagFilter(scope.row.status) "
              disable-transitions
              >{{ statusFilter(scope.row.status) }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('PUBLISH_TIME')"
          :label="$t('flyparam.param_file_publish_time')"
          prop="releaseTime"
          width="170px"
        >
          <template v-slot="scope">
            <span>{{ dateTimeFilter( scope.row.releaseTime ) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('UPDATE_SCHEDULE')"
          width="200px"
          :label="$t('menu.M_12401006')"
          prop="isInUpdateSchedule"
          align="center"
        >
          <template v-slot="scope">
            <el-tag v-if="scope.row.isInUpdateSchedule == 1" size="small">{{
              $t('flyparam.binding')
            }}</el-tag>
            <el-tag v-else size="small">{{ $t('flyparam.not_bind') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('FILE_PUBLISH_PROGRESS')"
          width="200px"
          :label="$t('flyparam.terminal_file_generate_queue')"
          prop="isFilePublishing"
          align="center"
        >
          <template v-slot="scope">
            <el-tag v-if="scope.row.isFilePublishing == 1" size="small">{{
              $t('flyparam.queue')
            }}</el-tag>
            <el-tag v-else size="small">{{
              $t('flyparam.not_in_queue')
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('common.operation')"
          width="100px"
          align="center"
        >
          <template v-slot="scope">
            <el-dropdown
              @command="(command) => handleCommand(command, scope.row)"
            >
              <span class="el-dropdown-link">
                <svg-icon icon-class="menu" style="font-size: 24px" />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-permission="{ permission: '12401620.CONFIGURATION' }"
                    command="edit"
                    icon="el-icon-edit"
                    >{{ $t('flyparam.edit') }}</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-permission="{ permission: PERMISSIONS.CONFIGURATION }"
                    command="copy"
                    icon="el-icon-document-copy"
                    >{{ $t('flyparam.copy') }}</el-dropdown-item
                  >
                  <el-dropdown-item command="compare" icon="el-icon-guide">{{
                    $t('flyparam.compare')
                  }}</el-dropdown-item>
                  <el-dropdown-item
                    command="download"
                    icon="el-icon-download"
                    >{{ $t('flyparam.download_file') }}</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-permission="{ permission: PERMISSIONS.CONFIGURATION }"
                    command="delete"
                    icon="el-icon-delete"
                    >{{ $t('flyparam.del') }}</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-show="scope.row.version != null"
                    command="preview"
                    icon="el-icon-view"
                    >{{ $t('flyparam.cfg_data_preview') }}</el-dropdown-item
                  >
                </el-dropdown-menu></template
              >
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <copy-dialog
        v-model="copyDialogVisible"
        :terminal="terminal"
        :title="$t('flyparam.copy_terminal')"
        type="terminal"
        @confirm="fetchData"
      />
      <parameter-edit-dialog
        type="terminalTable"
        v-model="parameterEditVisible"
        :table-id="tableId"
        :entity-name="entityName"
        :reference-table="referenceTable"
        :app-name="info.appName"
        :sn="entityName"
        :template-id="templateId"
        @save="fetchData"
      />

      <import-export-dialog
        :authorized="
          $store.getters.btnPermissions.includes(PERMISSIONS.CONFIGURATION)
        "
        v-model="importExportVisible"
        v-bind="$attrs"
        type="Terminal"
        :template-id="templateId"
        :tree-data="treeData"
        :table-id="entryId"
        :table-type="1"
        @requested="fetchData"
      />

      <new-terminal
        v-model="newTerminalVisible"
        :info="info"
        @confirm="(newEntry) => handleNewTerminal(newEntry)"
      />

      <compare-dialog
        :template-id="templateId"
        v-model="compareDialogVisible"
        :table-id="tableId"
        :entity-id="entityId"
        :entry-id="entryId"
        :compare-name="compareName"
      />
      <dryrun-terminal
        :reference-table="profileTableList"
        v-model="dryrunVisible"
        :profile-id="profileId"
        :profile-table-list="profileTableList.filter((_) => _.id === profileId)"
        @confirm="fetchData"
      />

      <preview-drawer
        ref="previewDrawer"
        size="60%"
        :show-action-bar="false"
        v-model="jsonDrawerVisible"
        :content="jsonStr"
        :file-type="previewDrawerFileType"
        :loading="previewDrawerLoading"
        @refresh="(fileType) => refreshPreview()"
      />

      <task-download v-model="taskDownloadVisible" />
    </el-card>
  </div>
</template>

<script>
import {
  getProfileEntryList,
  deleteProfileEntry,
  downloadParameterConfigFile,
  getTemplateTableList,
  getTableRelatedList,
  getProfileEntryPreview
} from '@/api/parameter'
import { mapGetters } from 'vuex'
import ParameterEditDialog from './parameter-edit-dialog.vue'
import { dateTimeFilter } from '@/filters'
import CopyDialog from './copy-dialog.vue'
import ImportExportDialog from './import-export-dialog.vue'
import CompareDialog from './compare-dialog.vue'
import NewTerminal from './new-terminal.vue'
import OrganizationSelect from '@/components/selects/organization-select'
import TableColumnFilter from '@/components/page-setting/table-column-filter'
import DryrunTerminal from './dryrun-terminal.vue'
import { i18n } from '@/lang'
import base64 from '@/utils/base64'
import PreviewDrawer from './preview-drawer'
import TaskDownload from './task-download.vue'
var formatXml = require('xml-formatter')

import { PERMISSIONS } from '@/components/common/const'

export default {
  components: {
    CopyDialog,
    ParameterEditDialog,
    ImportExportDialog,
    NewTerminal,
    CompareDialog,
    OrganizationSelect,
    TableColumnFilter,
    DryrunTerminal,
    PreviewDrawer,
    TaskDownload
  },
  props: {
    entryId: {
      type: String
    },
    info: {
      type: Object
    }
  },
  data() {
    return {
      PERMISSIONS: { ...Object.freeze(PERMISSIONS.FLY_PARAM) },
      form: {
        rowUniqueKeyLike: ''
      },
      org: '',
      dataMode: '',
      status: '',
      currentItem: {},
      importExportVisible: false,
      profileTableList: [],
      tableData: [],
      treeData: [],
      referenceTable: [],
      tableLoading: false,
      terminalRadio: '1',
      chooseTerminal: true,
      page: 1,
      pageSize: 10,
      total: 0,
      terminal: {},
      copyDialogVisible: false,
      parameterEditVisible: false,
      referenceEditVisible: false,
      newTerminalVisible: false,
      compareDialogVisible: false,
      selectReferenceVisible: false,
      dryrunVisible: false,
      refTableSchemaId: '',
      entityName: '',
      tableId: '',
      profileId: '',
      entityId: '',
      compareName: '',
      orgId: '',
      queryOrg: {},
      subOrgFlag: 1,
      templateId: this.$route.params.id,
      isInUpdateSchedule: null,
      isFilePublishing: null,
      settings: {
        conditions: [],
        columns: []
      },
      jsonDrawerVisible: false,
      jsonStr: '', // 预览的json数据
      previewDrawerFileType: 1,
      previewDrawerLoading: false,
      taskDownloadVisible: false
    }
  },
  computed: {
    ...mapGetters(['orgs']),
    settingList() {
      return {
        conditions: [
          {
            title: this.$t('flyparam.param_file_status'),
            code: 'STATUS'
          },
          {
            title: this.$t('common.organization'),
            code: 'ORGANIZATION'
          },
          {
            title: this.$t('menu.M_12401006'),
            code: 'UPDATE_SCHEDULE'
          },
          {
            title: this.$t('flyparam.terminal_file_generate_queue'),
            code: 'FILE_PUBLISH_PROGRESS'
          }
        ],
        columns: [
          {
            title: this.$t('flyparam.param_file_publish_time'),
            code: 'PUBLISH_TIME'
          },
          {
            title: this.$t('menu.M_12401006'),
            code: 'UPDATE_SCHEDULE'
          },
          {
            title: this.$t('flyparam.terminal_file_generate_queue'),
            code: 'FILE_PUBLISH_PROGRESS'
          }
        ]
      }
    },
    defaultSettings() {
      return {
        conditions: ['STATUS'],
        columns: ['PUBLISH_TIME']
      }
    },
    bindUpdateScheduleStates() {
      return [
        { label: this.$t('common.yes'), value: 1 },
        { label: this.$t('common.no'), value: 0 }
      ]
    },
    filePublishStates() {
      return [
        { label: this.$t('common.yes'), value: 1 },
        { label: this.$t('common.no'), value: 0 }
      ]
    }
  },

  mounted() {
    const userInfo = JSON.parse(
      localStorage.getItem(this.$store.getters.keys.storage.username)
    )
    this.orgId = userInfo.orgId
    this.fetchData()
    this.fetchTemplateTableList()
  },
  methods: {
    statusFilter(value) {
      if (value == null) value = 1
      const status = {
        1: i18n.t('flyparam.file_status_1'),
        2: i18n.t('flyparam.file_status_2'),
        3: i18n.t('flyparam.file_status_3'),
        4: i18n.t('flyparam.file_status_4'),
        5: i18n.t('flyparam.file_status_5')
      }
      return status[value]
    },
    contentFilter(row) {
      var value = row.status
      const status = {
        3:
          i18n.t('flyparam.param_file_download_time') +
          ': ' +
          dateTimeFilter(row.terminalUpdateTime),
        4:
          i18n.t('flyparam.param_file_update_time') +
          ': ' +
          dateTimeFilter(row.appUpdateTime),
        5:
          i18n.t('flyparam.param_file_update_time') +
          ': ' +
          dateTimeFilter(row.appUpdateTime)
      }
      return status[value]
    },
    tagFilter(value) {
      const tag = {
        1: '',
        2: 'success',
        3: 'info',
        4: 'warnig',
        5: 'danger'
      }

      return tag[value]
    },
    dateTimeFilter,
    bindUpdateScheduleStateChange(value) {
      this.isInUpdateSchedule = value
    },
    filePublishStateChange(value) {
      this.isFilePublishing = value
    },
    terminalChange() {},
    handleClose() {},
    handleNewTerminal(newEntry) {
      this.fetchData().then(() => {
        this.$store.commit('parameter/INCREMENT_DEV_COUNT', this.info.id)
        this.edit({ ...newEntry, tableSchemaId: newEntry.schema.id })
      })
    },
    handleCommand(command, row) {
      this[command](row)
    },
    copy(row) {
      this.copyDialogVisible = true
      this.terminal = row
    },
    compare(row) {
      this.compareDialogVisible = true
      this.tableId = row.tableSchemaId
      this.entityId = row.id
      this.compareName = row.name
    },
    edit(row) {
      this.parameterEditVisible = true
      this.tableId = row.tableSchemaId
      this.entityId = row.id
      this.entityName = row.name
    },
    download(row) {
      const loading = this.$loading({
        lock: true,
        text: this.$t('flyparam.please_wait'),
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      downloadParameterConfigFile(
        row.paramsTemplateId,
        row.tableSchemaId,
        row.id
      )
        .then((res) => {
          loading.close()
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = res.url
          link.onclick = 'javascript:void(0)'
          link.click()
        })
        .catch((err) => {
          this.$message.error(err.message)
          loading.close()
        })
    },
    preview(row) {
      this.tableId = row.tableSchemaId
      this.entityId = row.id
      this.refreshPreview()
    },
    refreshPreview() {
      this.jsonDrawerVisible = true
      this.previewDrawerLoading = true
      getProfileEntryPreview(this.templateId, this.tableId, this.entityId).then(
        (res) => {
          this.previewDrawerLoading = false
          this.previewDrawerFileType = res.fileType
          if (res.fileType === 1) {
            const decoded = base64.decode(res.previewData) || '{}'
            this.jsonStr = JSON.parse(decoded)
          } else if (res.fileType === 2) {
            this.jsonStr = res.previewData
            this.$refs.previewDrawer.decode(res.previewData)
          } else if (res.fileType === 3) {
            const xml = base64.decode(res.previewData)
            // const xml = formatXml(base64.decode(data.previewData))
            this.jsonStr = formatXml(xml, {
              indentation: '  ',
              filter: (node) => node.type !== 'Comment',
              collapseContent: true,
              lineSeparator: '\n'
            })
          }

          console.log(this.jsonStr)
        }
      )
    },
    delete(row) {
      this.$commonConfirm({
        title: this.$t('flyparam.delete_entry_title'),
        type: 'danger',
        content: this.$t('flyparam.delete_entry_warning', { label: row.name }),
        btnSureTitle: this.$t('common.delete'),
        onConfirm: (instance, done) => {
          instance.loading = true
          deleteProfileEntry(row.paramsTemplateId, row.tableSchemaId, row.id)
            .then((res) => {
              this.$message.success(this.$t('flyparam.delete_success'))
              done()
              this.$store.commit('parameter/DECREMENT_DEV_COUNT', this.info.id)
              this.fetchData()
            })
            .catch((e) =>
              this.$confirmError(e).then(() => {
                done()
              })
            )
        }
      })
    },
    fetchData() {
      this.tableLoading = true
      return new Promise((resolve, reject) => {
        getProfileEntryList(this.$route.params.id, this.entryId, {
          pageNo: this.page,
          pageSize: this.pageSize,
          rowUniqueKeyLike: this.form.rowUniqueKeyLike,
          subOrgFlag: this.subOrgFlag,
          orgId: this.queryOrg.orgId,
          fileReleaseStatus: this.status,
          isFilePublishing: this.isFilePublishing,
          isInUpdateSchedule: this.isInUpdateSchedule
        })
          .then((res) => {
            this.tableLoading = false
            this.tableData = res.data
            this.total = res.rows
            resolve(res)
          })
          .catch((err) => {
            this.tableLoading = false
            this.$message.error(err)
            reject(err)
          })
      })
    },
    currentChangeHandle(val) {
      this.page = val
      this.fetchData()
    },
    fetchTemplateTableList() {
      this.treeData.push({ ...this.info, id: this.info.entryId })

      getTemplateTableList(this.templateId)
        .then((data) => {
          this.profileTableList = data
          this.referenceTable = data

          const profile = data.find(
            (item) => item.id === this.treeData[0].entryId
          )
          this.profileId = profile.id
          getTableRelatedList(this.templateId, profile.id)
            .then((relatedTables) => {
              this.treeData[0] = {
                ...this.treeData[0],
                id: profile.id,
                name: profile.name,
                tableType: profile.tableType,
                children: relatedTables
                  .filter((_) => _.tableType === 1)
                  .map((item) => ({
                    id: item.id,
                    name: item.name,
                    tableType: item.tableType
                  }))
              }
            })
            .catch(this.$confirmError)
        })
        .catch(this.$confirmError)
    },

    handleAddTerminal() {
      this.newTerminalVisible = true
    },
    showHeader(label) {
      var list = this.settings['columns']
      return list ? list.includes(label) : false
    },
    showFormItem(label) {
      var list = this.settings['conditions']
      return list ? list.includes(label) : false
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/mixin.scss';

::v-deep {
  .el-form-item {
    @include formIcon;
  }

  .el-table th.el-table__cell > .cell {
    word-break: break-word;
  }
}
</style>
